package com.longcai.config;

import com.longcai.fifter.TokenFilters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

/**
 * @author zj
 * @Title: SecurityConfig
 * @ProjectName spring-cloud-media
 * @Description: TODO
 * @date 2019/2/2013:56
 */
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Qualifier("UserDetailsServiceImpl")
    @Autowired
    protected UserDetailsService UserDetailsService;
    @Autowired(required = false)
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired(required = false)
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Autowired(required = false)
    private LogoutSuccessHandler logoutSuccessHandler;
    @Autowired(required = false)
    private AuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    private TokenFilters tokenFilter;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        // 基于token，所以不需要session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.authorizeRequests()
                .antMatchers("/", "/*.html", "/oauth/**", "/v2/api-docs/**", "/favicon.ico",
                        "/static/**", "/pages/**").permitAll()
                .anyRequest().authenticated();   // 其他地址的访问均需验证权限
        http.formLogin().loginProcessingUrl("/login")
                .successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler).and()
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
        http.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
        // 解决不允许显示在iframe的问题
        http.headers().frameOptions().disable();
        http.headers().cacheControl();

        http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 权限控制需要忽略所有静态资源，不然登录页面未登录状态无法加载css等静态资源
        web.ignoring().antMatchers("/global/**");
        web.ignoring().antMatchers("/clyjUser/**");
        web.ignoring().antMatchers("/clyjUserPropertyRecord/**");
        web.ignoring().antMatchers("/clyjScmGoods/**");
        web.ignoring().antMatchers("/clyjUserProperty/**");
        web.ignoring().antMatchers("/goodsOrder/**");


    }

    /**
     * 用户认证
     *
     * @param auth
     */
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(UserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
